# Copyright Authors of Cilium
# SPDX-License-Identifier: Apache-2.0

MAKEFILE_VALUES?=Makefile.values
include $(MAKEFILE_VALUES)

include ../../Makefile.defs

ifeq ($(CILIUM_VERSION),)
export CILIUM_VERSION:=v$(VERSION)
endif

MIN_K8S_MAJOR := 1
MIN_K8S_MINOR := 16
MIN_K8S_VERSION := "v$(MIN_K8S_MAJOR).$(MIN_K8S_MINOR).0"

CILIUM_CHARTS := $(ROOT_DIR)/$(RELATIVE_DIR)/cilium
CHART_FILE := "$(CILIUM_CHARTS)/Chart.yaml"

VERSION_REGEX := '[0-9]\+\.[0-9]\+\.[0-9]\+.*'
CILIUM_CHART_REGEX := '\([vV]ersion:\) '$(VERSION_REGEX)

DOCKER_RUN := $(CONTAINER_ENGINE) container run --rm \
	--workdir /src/install/kubernetes \
	--volume $(CURDIR)/../..:/src \
	--user "$(shell id -u):$(shell id -g)"
HELM_DOCS := $(DOCKER_RUN) $(HELM_TOOLBOX_IMAGE) helm-docs
HELM := $(DOCKER_RUN) $(HELM_TOOLBOX_IMAGE) helm

LOGO_BASE_URL := https://cdn.jsdelivr.net/gh/cilium
LOGO_PATH := Documentation/images/logo-solo.svg

define generate_values_yaml
echo -e "# File generated by $(RELATIVE_DIR)/Makefile; DO NOT EDIT." > $(2); \
echo -e "# This file is based on $(RELATIVE_DIR)/cilium/values.yaml.tmpl.\n" >> $(2); \
envsubst < $(1) >> $(2)
endef

all: update-versions check-values-yaml docs lint

update-chart: $(ROOT_DIR)/VERSION # Update chart versions to point to the current version.
	$(ECHO_GEN)cilium/Chart.yaml
	$(QUIET)grep -lR -e 'version:' -e 'appVersion:' $(CILIUM_CHARTS)/ \
		| xargs -L 1 $(SED) -i -e 's/'$(CILIUM_CHART_REGEX)'/\1 '$(VERSION)'/g'
	$(QUIET)$(SED) -i 's;icon:.*;icon: $(LOGO_BASE_URL)/cilium@$(CILIUM_BRANCH)/$(LOGO_PATH);' $(CHART_FILE)

check-values-yaml:
	$(ECHO_CHECK) $@
	$(QUIET)( $(call generate_values_yaml,$(CILIUM_CHARTS)/values.yaml.tmpl,/dev/stdout) ) \
		| diff -u - "$(CILIUM_CHARTS)/values.yaml" \
		|| (echo -e "\nerror: cilium/values.yaml has been modified"; \
			echo "Make sure to apply your changes to cilium/values.yaml.tmpl and run 'make -C install/kubernetes cilium/values.yaml' to regenerate."; exit 1)

cilium/values.yaml: $(CILIUM_CHARTS)/values.yaml.tmpl $(ROOT_DIR)/VERSION $(ROOT_DIR)/$(RELATIVE_DIR)/Makefile.digests $(ROOT_DIR)/$(RELATIVE_DIR)/$(MAKEFILE_VALUES)
	$(ECHO_GEN)$@
	$(call generate_values_yaml,$<,$@)

update-versions: update-chart cilium/values.yaml # Update the Helm values file to point to the current version.

CRD_FILES := $(shell find $(ROOT_DIR)/examples/crds/*/ -type f)
CRDS := $(foreach path,$(patsubst %.yaml,%,$(CRD_FILES)),$(shell basename $(path)))
lint:
	$(ECHO_CHECK)
	$(QUIET)for crd in $(CRDS); do \
		grep -q $$crd $(CHART_FILE) \
		|| (echo -e "$$crd not found in $(CHART_FILE).\nPlease update the chart to include $$crd."; exit 1); \
	done
	$(QUIET)$(HELM) lint --with-subcharts --values ./cilium/values.yaml ./cilium

docs:
	$(QUIET)$(HELM_DOCS)

check-docker-images: # Check whether docker images are available for the current version.
	$(QUIET)$(ROOT_DIR)/contrib/release/check-docker-images.sh "$(CILIUM_VERSION)"

.PHONY: all check-docker-images check-values-yaml clean docs lint update-chart update-versions
